from evolution import *
import random
import Image

class EvolutionImage(Evolution):
	def __init__(self, signal, x, y):
		self.y = np.array(y)
		super(EvolutionImage, self).__init__(signal, x)

	def _generateInitialPopulation(self):
		temp = GeneTwoDim.initialisedGene(self.signal, self.x, self.y)
		maxDistance = temp.maxDistanceToSignal
		#TODO creer une classe signalData
		self.genes = [(GeneTwoDim.initialisedGene(self.signal, self.x, self.y), maxDistance) for x in xrange(self.nKeeped)]

if __name__ == '__main__':
	def getEstimation(x, y, signal):
		evolution = EvolutionImage(signal, x, y)
		evolution.startInThread()
		print "Absolute distance:", evolution.getDistanceToSignal()
		print "Relative distance:", evolution.getRelativeDistanceToSignal()
		#print "Estimated signal:", evolution.getEstimatedSignal()
		#print "Initial signal:", signal
		#print "Estimated rounded signal:", map(int, map(round, evolution.getEstimatedSignal()))
		print "Formula:", evolution.getFormula()
		res = list(evolution.getEstimatedSignal())
		rounder = lambda x: int(round(x))
		res = map(rounder, res)
		return res

#==================================================
	#r.seed(0)
	imageFileName = "rouge_small.jpg"
	image = Image.open(imageFileName)
	dataImage = list(image.getdata())
	width = image.size[0]
	height = image.size[1]
	x = []
	y = []
	redSignal = []
	greenSignal = []
	blueSignal = []
	for i, (r, g, b) in enumerate(dataImage):
		x.append(i%width)
		y.append(i/width)
		redSignal.append(r)
		greenSignal.append(g)
		blueSignal.append(b)

	print "width:", width
	print "heigth:", height
	print "n pixels:", width*height
	print "RED:"
	estRed = getEstimation(x, y, redSignal)
	print "GREEN:"
	estGreen = getEstimation(x, y, greenSignal)
	print "BLUE:"
	estBlue = getEstimation(x, y, blueSignal)

	dataNewImage = zip(estRed, estGreen, estBlue)
	newImage = Image.new(image.mode, image.size) 
	newImage.putdata(dataNewImage) 

	outImageFileName = imageFileName[:-4] + "_est" + imageFileName[-4:]
	newImage.save(outImageFileName)

